package com.aote.entity.component;

import java.util.Collection;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.browsesoft.Entity;
import com.browsesoft.EntityManager;
import com.browsesoft.Tools;
import com.browsesoft.baseadapter.AdvancedSimpleEntity;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.oa.DisposeSelectResult;

/**
 * 高级简单实体的关联对象选择组件
 */
public class AssociateEntitySelectComponent extends HTMLBasicComponent
		implements DisposeSelectResult {
	/**
	 * 要选择的实体属性名
	 */
	private String attrName;

	/**
	 * 要选择的实体
	 */
	private AdvancedSimpleEntity entity;

	/**
	 * 对应的实体类型
	 */
	private String entityType;

	public AssociateEntitySelectComponent(HTMLBasicComponent parent)
			throws Exception {
		super(parent);
	}

	public void init(HttpServletRequest request, Element e) throws Exception {
		super.init(request, e);
		// 得到要选择内容的实体
		this.entity = (AdvancedSimpleEntity) this.getParent().getModel();
		// 得到要选择的实体属性名
		attrName = e.getAttribute("property");
		// 得到要选择的实体类型
		this.entityType = e.getAttribute("entitytype");
		// 替换组件名参数
		String onclick = e.getAttribute("onclick");
		onclick = onclick.replaceAll("#compid#", this.getName());
		e.setAttribute("onclick", onclick);
	}

	public void dispose(String selectId) throws Exception {
		List ids = Tools.stringToLinkedList(selectId);
		// 选择的不是一个，不处理
		if (ids.size() != 1) {
			return;
		}
		// 找到实体，放到高级简单实体的关联实体中
		String id = (String) ids.get(0);
		Collection l = EntityManager.getInstance().getEntities(this.entityType,
				"id", id, this.getPage());
		Entity associate = (Entity) l.iterator().next();
		this.entity.setAssociateEntity(this.attrName, associate);
	}

	public void dispose(String name, String selectId) {
	}

	public void dispose(Hashtable ht) {
	}

	public String getDefaultValue() {
		// TODO Auto-generated method stub
		return null;
	}
}
